#!/bin/bash
# Copyright (c) 2020 Linaro Limited
#
# SPDX-License-Identifier: Apache-2.0

# Save off where we started so we can go back there
WORKDIR=${PWD}

ls -lsa .git

if [ -n "${BUILDKITE_PULL_REQUEST_BASE_BRANCH}" ]; then
   git fetch -v origin ${BUILDKITE_PULL_REQUEST_BASE_BRANCH}
   git checkout FETCH_HEAD
   git config --local user.email "builds@zephyrproject.org"
   git config --local user.name "Zephyr CI"
   git merge --no-edit "${BUILDKITE_COMMIT}" || {
       local merge_result=$?
       echo "Merge failed: ${merge_result}"
       git merge --abort
       exit $merge_result
   }
   ls -lsa .git
fi

mkdir -p /var/lib/buildkite-agent/zephyr-ccache/

# create cache dirs, no-op if they already exist
mkdir -p /var/lib/buildkite-agent/zephyr-module-cache/modules
mkdir -p /var/lib/buildkite-agent/zephyr-module-cache/tools
mkdir -p /var/lib/buildkite-agent/zephyr-module-cache/bootloader

# Clean cache - if it already exists
cd /var/lib/buildkite-agent/zephyr-module-cache
find -type f -not -path "*/.git/*" -not -name ".git" -delete

# Remove any stale locks
find -name index.lock -delete

# return from where we started so we can find pipeline files from
# git repo
cd ${WORKDIR}
